#import "CameraPreviewView.h"
#import <Masonry/Masonry.h>

@interface CameraPreviewView ()
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;

@property (nonatomic, strong) UILabel *countdownLabel;
@property (nonatomic, strong) UILabel *resultLabel;
@property (nonatomic, assign) CGFloat currentZoom;
@end

@implementation CameraPreviewView

#pragma mark - 懒加载控件
- (AVCaptureVideoPreviewLayer *)previewLayer {
    if (!_previewLayer) {
        _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:nil];
        _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        _previewLayer.frame = self.bounds;
        [self.layer addSublayer:_previewLayer];
    }
    return _previewLayer;
}

- (UILabel *)countdownLabel {
    if (!_countdownLabel) {
        _countdownLabel = [[UILabel alloc] init];
        _countdownLabel.textColor = [UIColor whiteColor];
        _countdownLabel.font = [UIFont boldSystemFontOfSize:48];
        _countdownLabel.textAlignment = NSTextAlignmentCenter;
        _countdownLabel.alpha = 0;
        [self addSubview:_countdownLabel];
        [_countdownLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self);
        }];
    }
    return _countdownLabel;
}
- (UILabel *)resultLabel {
    if (!_resultLabel) {
        _resultLabel = [[UILabel alloc] init];
        _resultLabel.textColor = [UIColor whiteColor];
        _resultLabel.font = [UIFont boldSystemFontOfSize:60];
        _resultLabel.textAlignment = NSTextAlignmentCenter;
        _resultLabel.alpha = 0;
        [self addSubview:_resultLabel];
        [_resultLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self);
        }];
    }
    return _resultLabel;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor blackColor];
        self.layer.masksToBounds = YES;
        self.layer.cornerRadius = 24;
        self.currentZoom = 1.0;
        // 只触发懒加载和布局
        [self previewLayer];
        [self countdownLabel];
        [self resultLabel];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    // 重新应用当前的缩放
    [self setZoom:self.currentZoom];
}

- (void)setupSession:(AVCaptureSession *)session {
    self.previewLayer.session = session;
}

- (void)setZoom:(CGFloat)zoom {
    self.currentZoom = zoom;
    
    if (zoom > 1.0) {
        // 放大时使用transform
        self.previewLayer.affineTransform = CGAffineTransformMakeScale(zoom, zoom);
        self.previewLayer.frame = self.bounds;
    } else {
        // 正常大小或缩小时，重置为原始状态
        self.previewLayer.affineTransform = CGAffineTransformIdentity;
        self.previewLayer.frame = self.bounds;
    }
}
- (void)setMirrored:(BOOL)mirrored {
    AVCaptureConnection *conn = self.previewLayer.connection;
    if (conn.isVideoMirroringSupported) {
        conn.automaticallyAdjustsVideoMirroring = NO;
        // 前置摄像头默认是镜像的，所以mirrored=YES时应该显示非镜像效果
        conn.videoMirrored = !mirrored;
    }
}
- (void)showCountdown:(NSInteger)seconds {
    self.countdownLabel.text = [NSString stringWithFormat:@"%ld", (long)seconds];
    self.countdownLabel.alpha = 1;
}
- (void)hideCountdown {
    self.countdownLabel.alpha = 0;
}
- (void)showResult:(BOOL)success {
    self.resultLabel.text = success ? @"✅" : @"❌";
    self.resultLabel.alpha = 1;
    [UIView animateWithDuration:0.8 delay:0.5 options:0 animations:^{
        self.resultLabel.alpha = 0;
    } completion:nil];
}
- (void)playLiveFlashEffect {
    // 只保留一个flashView
    UIView *flashView = [self viewWithTag:9999];
    if (!flashView) {
        flashView = [[UIView alloc] initWithFrame:self.bounds];
        flashView.backgroundColor = [UIColor whiteColor];
        flashView.alpha = 0.0;
        flashView.tag = 9999;
        [self addSubview:flashView];
    }
    [UIView animateWithDuration:0.1 animations:^{
        flashView.alpha = 1.0;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.2 animations:^{
            flashView.alpha = 0.0;
        } completion:^(BOOL finished) {
            [flashView removeFromSuperview];
        }];
    }];
}
@end 
